package com.test.deencredit.fragment_deencredit.ln_state_deencredit;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;

import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.test.deencredit.R;
import com.test.deencredit.activity_deencredit.ln_deencredit.MainActivity_deencredit;
import com.test.deencredit.base_deencredit.BaseLnFragment_deencredit;
import com.test.deencredit.bean_deencredit.config_deencredit.AppShowCustomize_deencredit;
import com.test.deencredit.bean_deencredit.config_deencredit.RecommendAppInfo_deencredit;
import com.test.deencredit.bean_deencredit.process_deencredit.ProcessInfo_deencredit;
import com.test.deencredit.bean_deencredit.star_dialog_deencredit.ActiveWindowConfig_deencredit;
import com.test.deencredit.bean_deencredit.star_dialog_deencredit.NormalWindowConfig_deencredit;
import com.test.deencredit.bean_deencredit.userinfo_deencredit.AccountList_Fr_deencredit;
import com.test.deencredit.bean_deencredit.userinfo_deencredit.BankAccount_Fr_deencredit;
import com.test.deencredit.bean_deencredit.userinfo_deencredit.LnAplyDetailInfo_deencredit;
import com.test.deencredit.bean_deencredit.userinfo_deencredit.OthersInfo_deencredit;
import com.test.deencredit.config_deencredit.CountryConfig_deencredit;
import com.test.deencredit.config_deencredit.UserState_deencredit;
import com.test.deencredit.dialog_deencredit.BindAccountChannelDialog_Fr_deencredit;
import com.test.deencredit.dialog_deencredit.BindAccountDialog_Fr_deencredit;
import com.test.deencredit.dialog_deencredit.CustomerServiceDialog_deencredit;
import com.test.deencredit.dialog_deencredit.DeleteAccountDialog_Fr_deencredit;
import com.test.deencredit.dialog_deencredit.RateActiveDialog_deencredit;
import com.test.deencredit.dialog_deencredit.RateNormalDialog_deencredit;
import com.test.deencredit.util_deencredit.UserInfoUtil_deencredit;
import com.test.deencredit.util_deencredit.http_deencredit.HttpUtil_deencredit;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

public class LnStateWaitFragment_deencredit extends BaseLnFragment_deencredit {

    private ImageView stateImageIv_deencredit;
    private TextView stateTitleTv_deencredit, stateTextTv_deencredit;
    private TextView lnAmountTv_deencredit, lnTermTv_deencredit;
    private View tipsView_deencredit;
    private TextView tipsTitleTv_deencredit, tipsTextTv_deencredit;
    private LinearLayout accountGroupLayout_deencredit;
    private View addAccountBtn_deencredit;
    private LinearLayout recommendAppGroupLayout_deencredit;

    private String bindChannelMobile_deencredit = "";

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        page_deencredit = "REVIEW";
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_ln_state_wait_deencredit, container, false);

        view.findViewById(R.id.flsw_ib_customerservice).setOnClickListener(v -> new CustomerServiceDialog_deencredit(requireContext()).show());

        SwipeRefreshLayout refreshLayout = view.findViewById(R.id.flsw_refreshlayout);
        refreshLayout.setOnRefreshListener(() -> {
            refreshLayout.setRefreshing(false);
            HttpUtil_deencredit.getInstance_deencredit().saveBuriedPoint_deencredit(page_deencredit,"REFRESH_CLICK","");
            HttpUtil_deencredit.getInstance_deencredit().userProcess_deencredit(requireActivity(),() -> {
                String state = ProcessInfo_deencredit.getInstance_deencredit().getUserState_deencredit();
                if (UserState_deencredit.isStateChange_deencredit(state)) {//刷新用户状态
                    FragmentActivity activity = requireActivity();
                    UserState_deencredit.clearState_deencredit();
                    activity.startActivity(new Intent(activity, MainActivity_deencredit.class));
                    activity.finish();
                }else HttpUtil_deencredit.getInstance_deencredit().requestLnAplyDetail_deencredit(requireActivity(),() -> HttpUtil_deencredit.getInstance_deencredit().requestAppSInfo_deencredit(requireActivity(),this::refresh_deencredit));
            });
        });

        view.findViewById(R.id.flsw_btn_refresh).setOnClickListener(v -> {
            HttpUtil_deencredit.getInstance_deencredit().saveBuriedPoint_deencredit(page_deencredit,"REFRESH_CLICK","");
            HttpUtil_deencredit.getInstance_deencredit().userProcess_deencredit(requireActivity(),() ->{
                String state = ProcessInfo_deencredit.getInstance_deencredit().getUserState_deencredit();
                if (UserState_deencredit.isStateChange_deencredit(state)) {//刷新用户状态
                    FragmentActivity activity = requireActivity();
                    UserState_deencredit.clearState_deencredit();
                    activity.startActivity(new Intent(activity, MainActivity_deencredit.class));
                    activity.finish();
                }else HttpUtil_deencredit.getInstance_deencredit().requestLnAplyDetail_deencredit(requireActivity(),() -> HttpUtil_deencredit.getInstance_deencredit().requestAppSInfo_deencredit(requireActivity(),this::refresh_deencredit));
            });
        });

        stateImageIv_deencredit = view.findViewById(R.id.flsw_iv_stateimg);
        stateTitleTv_deencredit = view.findViewById(R.id.flsw_tv_statetitle);
        stateTextTv_deencredit = view.findViewById(R.id.flsw_tv_statetext);
        lnAmountTv_deencredit = view.findViewById(R.id.flsw_tv_lnamount);
        lnTermTv_deencredit = view.findViewById(R.id.flsw_tv_lnterm);
        tipsView_deencredit = view.findViewById(R.id.flsw_view_tips);
        tipsTitleTv_deencredit = view.findViewById(R.id.flsw_tv_tipstitle);
        tipsTextTv_deencredit = view.findViewById(R.id.flsw_tv_tipstext);
        accountGroupLayout_deencredit = view.findViewById(R.id.flsw_layout_accountgroup);
        addAccountBtn_deencredit = view.findViewById(R.id.flsw_btn_addaccount);
        recommendAppGroupLayout_deencredit = view.findViewById(R.id.flsw_layout_recommendappgroup);

        init_deencredit();

        return view;
    }

    private void init_deencredit(){
        //初始化审核状态
        if (ProcessInfo_deencredit.getInstance_deencredit().isOrderLoaning_deencredit()){//状态：审核通过放款中
            page_deencredit = "LOANING";
            stateImageIv_deencredit.setBackgroundResource(R.drawable.img_ln_lning_deencredit);
            stateTitleTv_deencredit.setText(getString(R.string.ln_wait_lning_title_deencredit));
            stateTextTv_deencredit.setText(getString(R.string.ln_wait_lning_text_deencredit));
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        HttpUtil_deencredit.getInstance_deencredit().requestLnAplyDetail_deencredit(requireActivity(),() ->
                HttpUtil_deencredit.getInstance_deencredit().requestAppSInfo_deencredit(requireActivity(),this::refresh_deencredit)
        );
    }

    //更新额度、日期、推荐app显示
    @SuppressLint("SetTextI18n")
    public void refresh_deencredit(){
        String currency = LnAplyDetailInfo_deencredit.getInstance_deencredit().getCurrency_deencredit();

        lnAmountTv_deencredit.setText(LnAplyDetailInfo_deencredit.getInstance_deencredit().getAmount_deencredit()+" "+currency);
        lnTermTv_deencredit.setText(LnAplyDetailInfo_deencredit.getInstance_deencredit().getTermStr_deencredit(requireContext()));

        //提示文案显示
        if (LnAplyDetailInfo_deencredit.getInstance_deencredit().isShowWaitTips_deencredit()){
            tipsTitleTv_deencredit.setText(LnAplyDetailInfo_deencredit.getInstance_deencredit().getWaitTipsTitle_deencredit());
            tipsTextTv_deencredit.setText(LnAplyDetailInfo_deencredit.getInstance_deencredit().getWaitTipsText_deencredit());
            tipsView_deencredit.setVisibility(View.VISIBLE);
        }

        //app推荐显示
        refreshRecommendAppList_deencredit();

        //放款账户显示
        refreshAccounts_deencredit();

    }

    //放款账户显示
    private void refreshAccounts_deencredit(){

        accountGroupLayout_deencredit.removeAllViews();

        if (CountryConfig_deencredit.getInstance_deencredit().isGhana_deencredit()){//加纳

            View accountView = LayoutInflater.from(requireContext()).inflate(R.layout.item_account_show_deencredit,null);
            TextView accountTv = accountView.findViewById(R.id.ias_tv_account);
            accountTv.setText(LnAplyDetailInfo_deencredit.getInstance_deencredit().getWltMobile_Gh_deencredit());
            accountGroupLayout_deencredit.addView(accountView);
            afterFinishInit_deencredit();

        }else if (CountryConfig_deencredit.getInstance_deencredit().isFrench_deencredit()){//法语区

            addAccountBtn_deencredit.setVisibility(View.VISIBLE);
            addAccountBtn_deencredit.setOnClickListener(v -> {
                HttpUtil_deencredit.getInstance_deencredit().saveBuriedPoint_deencredit(page_deencredit,"ADD_CLICK","");
                new BindAccountDialog_Fr_deencredit(requireActivity(), page_deencredit,
                        mobile -> {
                            bindChannelMobile_deencredit = mobile;
                            HttpUtil_deencredit.getInstance_deencredit().requestAccountList_Fr_deencredit(requireActivity(),this::refreshAccountList_Fr_deencredit);
                        }
                ).show();
            });

            HttpUtil_deencredit.getInstance_deencredit().requestAccountList_Fr_deencredit(requireActivity(),this::refreshAccountList_Fr_deencredit);

        }else {//其他国家

            View accountView = LayoutInflater.from(requireContext()).inflate(R.layout.item_account_show_deencredit,null);
            TextView accountTv = accountView.findViewById(R.id.ias_tv_account);
            accountTv.setText(LnAplyDetailInfo_deencredit.getInstance_deencredit().getBkAccount_NiUgKe_deencredit());
            accountGroupLayout_deencredit.addView(accountView);
            afterFinishInit_deencredit();

        }
    }

    //更新法语区绑卡列表
    public void refreshAccountList_Fr_deencredit(){
        accountGroupLayout_deencredit.removeAllViews();

        ArrayList<BankAccount_Fr_deencredit> accounts = AccountList_Fr_deencredit.getInstance_deencredit().getBankAccountList_deencredit();

        int i=0;
        while (i<2 || i<accounts.size()){

            if (i<accounts.size()) addAccount_Fr_deencredit(accounts.get(i),i+1);
            else {
                View view = View.inflate(requireContext(), R.layout.item_add_account_fr_deencredit, null);
                TextView titleView = view.findViewById(R.id.iaaf_tv_title);
                titleView.append(" "+i);
                view.findViewById(R.id.iaaf_view_click).setOnClickListener(
                        v -> {
                            HttpUtil_deencredit.getInstance_deencredit().saveBuriedPoint_deencredit(page_deencredit,"ADD_CLICK","");
                            new BindAccountDialog_Fr_deencredit(requireActivity(), page_deencredit,
                                    mobile -> {
                                        bindChannelMobile_deencredit = mobile;
                                        HttpUtil_deencredit.getInstance_deencredit().requestAccountList_Fr_deencredit(requireActivity(),this::refreshAccountList_Fr_deencredit);
                                    }
                            ).show();
                        }
                );
                accountGroupLayout_deencredit.addView(view);
            }

            i++;
        }

        //更新列表后，判断是否需要绑定运营商
        if (!TextUtils.isEmpty(bindChannelMobile_deencredit) ){
            if (OthersInfo_deencredit.getInstance_deencredit().getAddBindFlag_deencredit()){
                new BindAccountChannelDialog_Fr_deencredit(requireContext(), bindChannelMobile_deencredit,
                        null,
                        () -> HttpUtil_deencredit.getInstance_deencredit().addAccount_Fr_deencredit(
                                    requireActivity(),
                                bindChannelMobile_deencredit,
                                bindChannelMobile_deencredit,
                                    OthersInfo_deencredit.getInstance_deencredit().getChannel_deencredit(),
                                    () -> HttpUtil_deencredit.getInstance_deencredit().requestAccountList_Fr_deencredit(requireActivity(),this::refreshAccountList_Fr_deencredit),
                                    false
                        )

                ).show();
                bindChannelMobile_deencredit = "";
            }
        }else afterFinishInit_deencredit();
    }

    //法语区添加放款卡
    private void addAccount_Fr_deencredit(BankAccount_Fr_deencredit account, int num){
        if (account == null) return;

        String desc = account.getWalletDesc_deencredit();

        View accountView = View.inflate(requireContext(), R.layout.item_account_fr_deencredit, null);
        TextView titleTv = accountView.findViewById(R.id.iaf_tv_title);
        ImageView logoIv = accountView.findViewById(R.id.iaf_iv_logo);
        TextView channelTv = accountView.findViewById(R.id.iaf_tv_channel);
        TextView mobileTv = accountView.findViewById(R.id.iaf_tv_mobile);
        ImageButton deleteIb = accountView.findViewById(R.id.iaf_ib_delete);

        titleTv.append(" "+num);
        mobileTv.setText(account.getWalletMobile_deencredit());
        channelTv.setText(desc);

        //删除卡
        deleteIb.setOnClickListener(v -> {
            HttpUtil_deencredit.getInstance_deencredit().saveBuriedPoint_deencredit(page_deencredit,"DELETE_CLICK",account.getWalletMobile_deencredit());
            new DeleteAccountDialog_Fr_deencredit(requireActivity(),account, page_deencredit,
                    () -> HttpUtil_deencredit.getInstance_deencredit().requestAccountList_Fr_deencredit(requireActivity(),this::refreshAccountList_Fr_deencredit)).show();
        });

        accountGroupLayout_deencredit.addView(accountView);

        //获取图标
        if (AppShowCustomize_deencredit.getInstance_deencredit().getChannelLogoByDesc_deencredit(desc) == null){
            new Thread(() -> {
                try {
                    if (TextUtils.isEmpty(account.getWalletLogo_deencredit())) return;
                    if (!AppShowCustomize_deencredit.getInstance_deencredit().hasAccountChannel_deencredit()) return;
                    URL url = new URL(account.getWalletLogo_deencredit());
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(5000);
                    connection.setRequestMethod("GET");
                    if (connection.getResponseCode()==200){
                        InputStream inputStream = connection.getInputStream();
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        AppShowCustomize_deencredit.getInstance_deencredit().setChannelLogoByDesc_deencredit(desc,bitmap);
                        new Handler(Looper.getMainLooper()).post(() -> logoIv.setImageBitmap(bitmap));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }else logoIv.setImageBitmap(AppShowCustomize_deencredit.getInstance_deencredit().getChannelLogoByDesc_deencredit(desc));

    }

    //页面显示初始化结束后获取评分弹窗配置
    private void afterFinishInit_deencredit(){
        HttpUtil_deencredit.getInstance_deencredit().requestStarWindowConfig_deencredit(requireActivity(),this::onStarWindowConfigResponse_deencredit);
    }

    //评分弹窗显示流程
    public void onStarWindowConfigResponse_deencredit(){
        
        //1.活动弹窗
        if (ActiveWindowConfig_deencredit.getInstance().isSwitch_deencredit() &&
                UserInfoUtil_deencredit.getInstance_deencredit().getActivedialogCount_deencredit()< ActiveWindowConfig_deencredit.getInstance().getNum_deencredit()){
            new RateActiveDialog_deencredit((AppCompatActivity) requireActivity()).show();
            return;
        }

        //2.评价弹窗
        if (NormalWindowConfig_deencredit.getInstance().isSwitch_deencredit() &&
                UserInfoUtil_deencredit.getInstance_deencredit().getNormaldialogCount_deencredit()< NormalWindowConfig_deencredit.getInstance().getNum_deencredit()){
            new RateNormalDialog_deencredit((AppCompatActivity) requireActivity()).show();
        }

    }
    
    public void refreshRecommendAppList_deencredit(){
        if (!AppShowCustomize_deencredit.getInstance_deencredit().getRecommendFlag_deencredit()) return;
        recommendAppGroupLayout_deencredit.removeAllViews();
        ArrayList<RecommendAppInfo_deencredit> recommendAppInfos = AppShowCustomize_deencredit.getInstance_deencredit().getRecommendAppList_deencredit();
        for (RecommendAppInfo_deencredit recommendAppInfo:recommendAppInfos){
            addRecommendApp_deencredit(recommendAppInfo);
        }
    }

    private void addRecommendApp_deencredit(RecommendAppInfo_deencredit recommendAppInfo){
        View itemView = LayoutInflater.from(requireContext()).inflate(R.layout.item_recommend_app_deencredit,null);

        TextView titleTv = itemView.findViewById(R.id.ira_tv_title);
        TextView textTv = itemView.findViewById(R.id.ira_tv_text);
        ImageView logoIv = itemView.findViewById(R.id.ira_iv_logo);
        TextView appNameTv = itemView.findViewById(R.id.ira_tv_appname);
        TextView amountTextTv = itemView.findViewById(R.id.ira_tv_amounttext);
        TextView scoreTv = itemView.findViewById(R.id.ira_tv_score);
        TextView downloadsTv = itemView.findViewById(R.id.ira_tv_downloads);

        titleTv.setText(recommendAppInfo.getTitle_deencredit(requireContext()));
        textTv.setText(recommendAppInfo.getText_deencredit(requireContext()));
        appNameTv.setText(recommendAppInfo.getAppName_deencredit());
        amountTextTv.setText(recommendAppInfo.getAmountText_deencredit());
        scoreTv.setText(recommendAppInfo.getScore_deencredit());
        downloadsTv.setText(recommendAppInfo.getDownloads_deencredit());

        //Install按键
        itemView.findViewById(R.id.ira_btn_install).setOnClickListener(v -> {
            HttpUtil_deencredit.getInstance_deencredit().saveBuriedPoint_deencredit(page_deencredit,"RECOMMEND_"+recommendAppInfo.getAppName_deencredit().toUpperCase()+"_INSTALL_CLICK","");
            String path = recommendAppInfo.getPath_deencredit();
            if (!TextUtils.isEmpty(path))
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(path)));
        });

        //加载logo
        if (recommendAppInfo.getLogoBitmap_deencredit()==null){
            new Thread(() -> {
                try {
                    String logoPath = recommendAppInfo.getLogo_deencredit();
                    if (TextUtils.isEmpty(logoPath)) return;
                    URL url = new URL(logoPath);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(5000);
                    connection.setRequestMethod("GET");
                    if (connection.getResponseCode()==200){
                        InputStream inputStream = connection.getInputStream();
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        recommendAppInfo.setLogoBitmap_deencredit(bitmap);
                        new Handler(Looper.getMainLooper()).post(() -> logoIv.setImageBitmap(bitmap));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }else logoIv.setImageBitmap(recommendAppInfo.getLogoBitmap_deencredit());

        recommendAppGroupLayout_deencredit.addView(itemView);
    }

}